package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.dao.OrderDetailRepisotry;
import com.qf.dao.OrderMapper;
import com.qf.dao.OrderRepository;
import com.qf.pojo.entity.QfOrder;
import com.qf.pojo.entity.QfOrderDetail;
import com.qf.pojo.entity.QfOrderVo;
import com.qf.pojo.repVo.BaseResp;
import com.qf.pojo.repVo.QfCourseRepVo;
import com.qf.pojo.reqVo.OrderReq;
import com.qf.service.OrderService;
import com.qf.utils.GenerateOrderNum;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    OrderDetailRepisotry orderDetailRepisotry;
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    JwtUtils jwtUtils;
    private static final  String SHOP_CARD_="shop_card_";

    @Override
    //使用事务来控制 总订单以及 订单详情
    @Transactional
    public BaseResp addOrder(OrderReq orderReq, HttpServletRequest request) {
        //1.解析出当前登录的用户
        Integer userid = jwtUtils.verfiy(request.getHeader("token"));
        //2.获取到该用户的购物车
        List ids = orderReq.getIds();
        //定义总的价格
        Double totalMoney=0.0;
        for (Object id: ids
             ) {
            Object o = redisTemplate.opsForHash().get(SHOP_CARD_ + userid.toString(), id.toString());
            //转为课程
            String s = JSONObject.toJSONString(o);
            QfCourseRepVo qfCourseRepVo = JSONObject.parseObject(s, QfCourseRepVo.class);
            totalMoney+=qfCourseRepVo.getPay();
        }
        //进行价格的比对，将前端的传入的价格与后端进行比对，保证数据的安全性
        //compareTo 如果d1>d2 返回1  如果d1<d2 返回 -1 ，如果相等则为0
        if (orderReq.getMoney().compareTo(totalMoney)!=0){
            return new BaseResp(0,"价格出错！",null,null);
        }
        //价格比对通过，生成总订单号
        String orderId=new  GenerateOrderNum().generate("");
        //拼接总订单的信息，进行入库处理
        QfOrder qfOrder = new QfOrder();
        qfOrder.setOrderid(orderId);
        qfOrder.setOrderPay(totalMoney);
        qfOrder.setUserid(userid);
        qfOrder.setOrderStatus(1);
        qfOrder.setCreatetime(new Date());
        //将总订单入库处理
        orderRepository.save(qfOrder);
        //生成订单详情信息，订单详细根据前端传入的课程id进行生成，有几个课程，生成几个订单
        for (Object id: ids
        ) {
            Object o = redisTemplate.opsForHash().get(SHOP_CARD_ + userid.toString(), id.toString());
            //转为课程
            String s = JSONObject.toJSONString(o);
            QfCourseRepVo qfCourseRepVo = JSONObject.parseObject(s, QfCourseRepVo.class);
           //拼接订单详细信息
            QfOrderDetail qfOrderDetail = new QfOrderDetail();
            qfOrderDetail.setOrderid(orderId);
            qfOrderDetail.setCourseid(Integer.valueOf(id.toString()));
            String orderDetailId=new  GenerateOrderNum().generate("");
            qfOrderDetail.setOrderDetailId(orderDetailId);
            qfOrderDetail.setCreatetime(new Date());
            //拼接完成后，进行入库
            orderDetailRepisotry.save(qfOrderDetail);
            //订单生成后，可以将生成订单的课程移除出redis购物车
            redisTemplate.opsForHash().delete(SHOP_CARD_ + userid.toString(),id.toString());
        }


        return new BaseResp(1,"生成订单成功！",null,null);
    }

    @Override
    public BaseResp findOrderByUserId(HttpServletRequest request) {
        //解析request获取到用户的id
        //1.解析出当前登录的用户
        Integer userid = jwtUtils.verfiy(request.getHeader("token"));
        //获取到该用户的未支付订单
        List<QfOrderVo> orderVoLIst =orderMapper.findOrderAndOrderDetailsByUserId(userid);
        return new BaseResp(1,"查询成功 ！",orderVoLIst,null);
    }

    @Override
    public BaseResp findByOrderid(String orderid) {

        Optional<QfOrder> byId = orderRepository.findById(orderid);
        if (!byId.isPresent()){
            return new BaseResp(0,"订单查询失败！",null,null);
        }
        return new BaseResp(1,"查询成功！",byId.get(),null);
    }

    @Override
    public BaseResp updateStatus(String orderid, int i) {
        //1.先查询出该订单的信息
        Optional<QfOrder> byId = orderRepository.findById(orderid);
        if (!byId.isPresent()){
            return new BaseResp(0,"订单查询失败！",null,null);
        }
        QfOrder qfOrder = byId.get();
        qfOrder.setOrderStatus(i);
        //将订单状态更改未传入的内容
        orderRepository.saveAndFlush(qfOrder);
        return new BaseResp(1,"更改成功!",null,null);
    }
}
